package org.mzy.order.mq;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.mzy.basic.config.BussinessException;
import org.mzy.order.domain.OrderPetAcquisition;
import org.mzy.order.service.IOrderPetAcquisitionService;
import org.mzy.pet.domain.SearchMasterMsg;
import org.mzy.pet.service.ISearchMasterMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消费者，消费了消息就修改订单状态
 */
@Component
@RocketMQMessageListener(consumerGroup = "pethome_consumer_group", topic = "pethome_topic")
public class PetMq implements RocketMQListener<String> {

    @Autowired
    private ISearchMasterMsgService searchMasterMsgService;

    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;

    @Override
    public void onMessage(String message) {
        System.out.println(message);
        // 参数校验
        if (message == null) {
            throw new BussinessException("该订单不存在");
        }
        // 根据订单编号获取订单信息
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionService.findByOrderSn(Long.valueOf(message));
        if (orderPetAcquisition == null){
            throw new BussinessException("该订单不存在");
        }
        // 若订单状态为0，则将状态改为取消，并更新订单
        if(orderPetAcquisition.getState() == 0){
            orderPetAcquisition.setState(-1);
            orderPetAcquisitionService.update(orderPetAcquisition);
            // 根据寻主信息id查询寻主消息
            SearchMasterMsg msg = searchMasterMsgService.findById(orderPetAcquisition.getSearchMasterMsgId());
            // 参数校验
            if (msg == null){
                throw new BussinessException("该寻主不存在！");
            }
            // 置空shopId，状态改为1，待审核
            msg.setShopId(null);
            msg.setState(1);
            // 更新寻主消息
            searchMasterMsgService.update(msg);
        }
    }
}